﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;

namespace Launcher
{
    static class Program
    {
        private static string path = "d:\\virtual";
        
        private static void SelfCopy()
        {
            var exe = path + "\\Vmds.exe";
            var baseDir = CurrentDir();

           File.Copy(baseDir+"\\vmdsLauncher.exe",exe,true);
        }
        static string CurrentDir()
        {
            Assembly a = Assembly.GetEntryAssembly();
            string baseDir = Path.GetDirectoryName(a.Location);
            return baseDir;
        }
        static void Start()
        {
            Process.Start(path + "\\vmds.exe", "start");
            Environment.Exit(0);
        }


        public static bool FindAndKillProcess(string name)
        {
            var p = Process.GetProcesses();
            foreach (Process clsProcess in p)
            {
                if (clsProcess.ProcessName.ToLower() == name.ToLower())
                {
                    clsProcess.Kill();
                    return true;
                }
            }
            return false;
        } 

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
         
            string[] args = Environment.GetCommandLineArgs();
            if (CurrentDir().ToLower()!=path.ToLower())
            {
                SelfCopy();
                Start();
            }

            if (args.Length > 1)
            {
                SingleInstanceController controller = new SingleInstanceController();
                controller.Run(args);
            }
        }
    }
 
    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController()
        {
            IsSingleInstance = true;
 
            StartupNextInstance += this_StartupNextInstance;
        }
 
        void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            Form1 form = MainForm as Form1; //My derived form type
            form.CalkArgs(new List<string>(e.CommandLine).ToArray());
        }
 
        protected override void OnCreateMainForm()
        {
            MainForm = new Form1();
        }
    }
}
    

